package wordcount;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;

import java.io.*;

public class word {
	
	private static int code = 0;
    private static int codeComments = 0;
	private static int codeBlank = 0;
	private static String selectType ;
	
	private static boolean flag = true; // 循环输入标志
	private static String selectResult;
	private static String[] splitStr;
	private static int len;
	private static String str;
	private static String ch = null;
	private static String word = null;
	private static String line = null;
	private static String refer = null;
	private static String Code =null;
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		
		//System.out.println("请输入：");
		while (flag) {
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			str = in.readLine(); // 按行读
			if (str.equals("2")) { // 等于2结束循环输入
				flag = false;
				System.out.println("结束了。。。");
				break;
			}
			if (str.length() > 1) {
				// 数组
				splitStr = str.split(" "); // 按空格分成数组
				len = splitStr.length; // 数组长度
				if (!str.contains("wc.exe")) {
					System.out.println("错误:缺少wc.exe");
					break;					
				}
				if(str.contains("-s")) {
					//System.out.println(splitStr[2]);
					selectType = splitStr[2];
					circleNum(".//");
				}else {
				for(int strIndex=0;strIndex<len;strIndex++) {
					selectResult = selectC(splitStr, ".c");
					switch(splitStr[strIndex]) {
					case "-c": ch = characterNum(selectResult);break;
					case "-w": word =wordNum(selectResult);break;
					case "-l": line =lineNum(selectResult);break;
					case "-o": writeFile(splitStr[splitStr.length - 1],ch ,word ,line,Code,refer);break;
					case "-a": Code=codeNum(selectResult);break;
					case "-e": refer=referWord(selectResult,splitStr[selectTxt(splitStr,"-e")]);break;
					}
					if(strIndex==len-1) {
						ch =null;word=null;line=null;Code=null;  
						refer=null;
					    code = 0; codeComments = 0;codeBlank = 0;
					  
					}
				
				}
				}
				System.out.println("--------------------------");
				System.out.println("-输入2:结束操作-");
			}
		}

	}


	// 字符数
	public static String characterNum(String fileName) throws IOException {
		File file = new File(fileName);
		int x = 0;
		if (file.exists()) {
			String path = file.getAbsolutePath();// 得到exe的文件路径
			FileReader fr = new FileReader(path);
			BufferedReader br = new BufferedReader(fr);
			String str;
			char[] ch = new char[300000];
			int len = 0;

			while ((len = br.read(ch)) != -1) {
				x = len;
				// System.out.println(ch[len]);
			}
			fr.close();
			br.close();
			System.out.println(fileName+",字符数:" + x);
			writeResult(fileName+",字符数:" + x + "\r\n");
			if (!(x != 0)) {
				x = x + 1;
			}
		}

		return fileName+",字符数:" + x+ "\r\n";
	}

	// 单词数
	public static String wordNum(String fileName) throws IOException {
		File file = new File(fileName);
		int total = 0;
		if (file.exists()) {
			String path = file.getAbsolutePath();// 得到exe的文件路径
			FileReader fr = new FileReader(path);
			BufferedReader br = new BufferedReader(fr);
			String str;
			int line = 0;
			ArrayList array = new ArrayList();
			while ((str = br.readLine()) != null) {
				str = str.replaceAll("[(\\u4e00-\\u9fa5)]", "");// 去除汉字
				str = str.replaceAll(",", " "); // 去除空格
				String[] str1 = str.split("\\s+"); // 按空格分割
				array.add(str1); // 放入集合
				line++;
			}
			fr.close();
			br.close();

			String regex = ".*[a-zA-Z]+.*"; // 正则判断每个数组中是否存在有效单词(存在字母)
			Pattern p = Pattern.compile(regex);
			Iterator it = array.iterator();
			while (it.hasNext()) {
				String[] string = (String[]) it.next();
				for (int y = 0; y <= string.length - 1; y++) {
					Matcher m = p.matcher(string[y]);
					if (m.matches()) {
						total++; // 每存在一个total加1
					}
				}
			}
			System.out.println(fileName+",单词数：" + total);
			writeResult(fileName+",单词数：" + total + "\r\n");
			
		}

		return fileName+",单词数：" + total+ "\r\n";
	}

	// 行数
	public static String lineNum(String fileName) throws IOException {
		File file = new File(fileName);
		int line = 0;
		if (file.exists()) {
			String path = new File(fileName).getAbsolutePath();// 得到exe的文件路径
			FileReader fr = new FileReader(path);
			BufferedReader br = new BufferedReader(fr);
			while (br.readLine() != null) { // 按行读取，每存在一行line+1
				line++;
			}
			fr.close();
			br.close();
			System.out.println(fileName+",行数:" + line);
			writeResult(fileName+",行数:" + line + "\r\n");
			if (!(line != 0)) {
				line = line + 1;
			}
		}

		return fileName+",行数:" + line+ "\r\n";
	}

	public static String codeNum(String fileName) throws IOException {
		File file = new File(fileName);
		BufferedReader br = null;
		String fileStr = null;
		try {
			br = new BufferedReader(new FileReader(file));
			boolean comm = false;
			while ((fileStr = br.readLine()) != null) {// 判断注释
				if (fileStr.startsWith("/*") && fileStr.endsWith("*/")) {
					codeComments++;
				} else if (fileStr.trim().startsWith("//")) {
					codeComments++;
				} else if (fileStr.startsWith("/*") && !fileStr.endsWith("*/")) {
					codeComments++;
					comm = true;
				} else if (!fileStr.startsWith("/*") && fileStr.endsWith("*/")) {
					codeComments++;
					comm = false;
				} else if (fileStr.indexOf('}') != -1 && fileStr.indexOf("//") != -1) {// 判断特殊注释'}//'
					codeComments++;
				} else if (fileStr.indexOf('{') != -1 && fileStr.indexOf("//") != -1) {// 判断特殊注释'{//'
					codeComments++;
				} else if (comm) {
					codeComments++;
				} else if (fileStr.trim().length() < 1 || fileStr.trim().length() == 1) {// 判断空行
					codeBlank++;
				} else if (fileStr.trim().length() != 1) {// 判断代码行
					code++;
				}
			}
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String codeStr = fileName + ",代码行数:" + code + "\r\n" + fileName + ",空白行数:" + codeBlank + "\r\n" + fileName
				+ ",注释行数:" + codeComments;
		System.out.println(codeStr);
		writeResult(codeStr + "\r\n");
		return codeStr + "\r\n";

	}

	public static void circleNum(String path) throws IOException { // path为目录
		File file = new File(path);
		if (file.isDirectory()) {
			File[] files = file.listFiles(); // 遍历该目录所有文件和文件夹对象
			for (int fileIndex = 0; fileIndex < files.length; fileIndex++) {

				if (files[fileIndex].isDirectory()) {
					circleNum(files[fileIndex].toString()); // 递归操作，逐一遍历各文件夹内的文件
				} else {
					if (!files[fileIndex].isDirectory()) {
						if (files[fileIndex].getName().endsWith(selectType)) {
							System.out.println(files[fileIndex].getName());
							for (int strIndex = 0; strIndex < len; strIndex++) {
								switch (splitStr[strIndex]) {
								case "-c":
									ch = characterNum(files[fileIndex].getName());
									break;
								case "-w":
									word = wordNum(files[fileIndex].getName());
									break;
								case "-l":
									line = lineNum(files[fileIndex].getName());
									break;
								case "-o":
									writeFile(splitStr[splitStr.length - 1], ch, word, line, Code, refer);
									break;
								case "-a":
									Code = codeNum(files[fileIndex].getName());
									break;
								}
								if (strIndex == len - 1) {
									ch = null;
									word = null;
									line = null;
									Code = null;
									code = 0;
									codeComments = 0;
									codeBlank = 0;
								}

							}
						}
					}
				}
			}
		}

	}

	public static String referWord(String fileName, String referFile) throws IOException {
		File file = new File(fileName);
		File refile = new File(referFile);
		int total = 0;
		if (file.exists()) {
			String path = file.getAbsolutePath();// 得到exe的文件路径
			FileReader fr = new FileReader(path);
			BufferedReader br = new BufferedReader(fr);
			BufferedReader rfbr = new BufferedReader(new FileReader(refile.getAbsolutePath()));
			String str;
			String rfstr;
			// int line = 0;
			ArrayList array = new ArrayList();
			ArrayList rfarray = new ArrayList();
			while ((str = br.readLine()) != null) {
				str = str.replaceAll("[(\\u4e00-\\u9fa5)]", "");// 去除汉字
				str = str.replaceAll(",", " "); // 去除空格
				String[] str1 = str.split("\\s+"); // 按空格分割
				array.add(str1); // 放入集合
			}
			while ((rfstr = rfbr.readLine()) != null) {
				rfarray.add(rfstr); // 放入集合
			}
			fr.close();
			br.close();
			rfbr.close();

			String regex = ".*[a-zA-Z]+.*"; // 正则判断每个数组中是否存在有效单词(存在字母)
			Pattern p = Pattern.compile(regex);
			Iterator it = array.iterator();

			while (it.hasNext()) {
				String[] string = (String[]) it.next();
				for (int y = 0; y <= string.length - 1; y++) {
					Matcher m = p.matcher(string[y]);
					if (m.matches()) {
					if(!rfarray.isEmpty()) {
					Iterator rfit = rfarray.iterator();
					
						while (rfit.hasNext()) {
							String rfstring = (String) rfit.next();
							if (rfstring.contains(string[y])) {
								break;
							}
							if (!rfit.hasNext()&&!rfstring.contains(string[y])) {
								System.out.println(string[y]);
								total=total+1;
							}
						}
					}else {
						total++;
					}
						
					}
				}
				System.out.println(fileName + ",筛选后的单词数：" + total);
				writeResult(fileName + ",筛选后的单词数：" + total + "\r\n");

			}
		}
		return fileName + ",筛选后的单词数：" + total + "\r\n";
	}
	
	// 写进指定文件
	public static void writeFile(String targetFile, String ch ,String word,String line,String Code,String refer) throws IOException {

		String path = new File(targetFile).getAbsolutePath(); // 得到目标文件路径
		FileWriter fw = new FileWriter(path, true);
		if(ch!=null) {
			fw.write(ch);
		}
		if(word!=null) {
			fw.write(word);
		}
		if(line!=null) {
			fw.write(line);
		}
		if(Code!=null) {
			fw.write(Code);
		}
		if(refer!=null) {
			fw.write(refer);
		}
		if (fw != null) {
			fw.close();
			//System.out.println("成功！");
		}

	}

	// 自动写入result.txt文件中
	public static void writeResult(String string) throws IOException {

		String path = new File("result.txt").getAbsolutePath();
		FileWriter fw = new FileWriter(path, true);
		fw.write(string);
		if (fw != null) {
			fw.close();
		}
	}

	// 返回.c文件名
	public static String selectC(String[] str, String target) {
		int index = 0;
		for (; index < str.length; index++) {
			if (str[index].contains(target)) {
				break;
			}
		}
		return str[index];
	}

	public static int selectTxt(String[] str, String target) {
		int index = 0;
		for (; index < str.length; index++) {
			if (str[index].contains(target)) {
				break;
			}
		}
		return index + 1;
	}

}

